package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.entity.UserInfo;
import org.jeecg.modules.system.entity.UserInfoEntity;
import org.jeecg.modules.system.mapper.UserInfoMapper;
import org.jeecg.modules.system.service.IUserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author yaojia
 * @since 2024-07-31 16:23
 **/
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfoEntity> implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfoEntity getUserInfo(String userID) {
        return userInfoMapper.selectOne(new QueryWrapper<UserInfoEntity>().lambda().eq(UserInfoEntity::getUserId, userID));
    }

    @Override
    public UserInfoEntity modifyUserInfo(UserInfo userInfo) {

        String userId = userInfo.getUserId();
        UserInfoEntity existUserInfo = getUserInfo(userId);

        if (Objects.isNull(existUserInfo)) {
            UserInfoEntity entity = new UserInfoEntity();
            BeanUtils.copyProperties(userInfo, entity);
            String membersListStr = JSONArray.toJSONString(userInfo.getMembersList());
            entity.setMembersList(membersListStr);
            userInfoMapper.insert(entity);
            existUserInfo = entity;
        } else {
            BeanUtils.copyProperties(userInfo, existUserInfo);
            String membersListStr = JSONArray.toJSONString(userInfo.getMembersList());
            existUserInfo.setMembersList(membersListStr);
            LambdaUpdateWrapper<UserInfoEntity> updateWrapper = new UpdateWrapper().lambda();
            updateWrapper.eq(UserInfoEntity::getUserId, userId);
            userInfoMapper.update(existUserInfo, updateWrapper);
        }

        return existUserInfo;
    }
}
